using System;
using System.Diagnostics;
using System.IO;

namespace Xtee.Core.Mime.Encoding
{
    public class Base64Decoder : Decoder
    {
       





        public override void Decode(byte[] chars, int startPos, int len)
        {
            byte[] nextBuffer = new byte[len];
            this.SetNextOutputBuffer(nextBuffer, 0, nextBuffer.Length);



            Debug.Assert(chars != null);
            Debug.Assert(len >= 0);
            Debug.Assert(startPos >= 0);
            Debug.Assert(chars.Length - startPos >= len);

            if (len == 0)
            {
                return ;
            }
            unsafe
            {
                int bytesDecoded, charsDecoded;
                fixed (byte* pChars = &chars[startPos])
                {
                    fixed (byte* pBytes = &buffer[curIndex])
                    {
                        Decode(pChars, pChars + len, pBytes, pBytes + (endIndex - curIndex), out charsDecoded, out bytesDecoded);
                    }
                }
                curIndex += bytesDecoded;
                this.outputStream.Write(nextBuffer, 0, bytesDecoded);
            }
           

           
            //  return charsDecoded;
           
        }




        //
// Fields
//
        byte[]  buffer;
        int     startIndex;
        int     curIndex;
        int     endIndex;

        int     bits;
        int     bitsFilled;

        private static readonly String CharsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        private static readonly byte[] MapBase64 = ConstructMapBase64();
        private const int MaxValidChar = (int)'z';
        private const byte Invalid = unchecked((byte)-1);

//
// IncrementalReadDecoder interface
//
        internal   int DecodedCount { 
            get { 
                return curIndex - startIndex; 
            } 
        }

        internal   bool IsFull { 
            get { 
                return curIndex == endIndex; 
            } 
        }

        //internal  unsafe int Decode( char[] chars, int startPos, int len ) {
        //    Debug.Assert( chars != null );
        //    Debug.Assert( len >= 0 );
        //    Debug.Assert( startPos >= 0 );
        //    Debug.Assert( chars.Length - startPos >= len );

        //    if ( len == 0 ) {
        //        return 0;
        //    }
        //    int bytesDecoded, charsDecoded;
        //    fixed ( char* pChars = &chars[startPos] ) {
        //        fixed ( byte* pBytes = &buffer[curIndex] ) {
        //            Decode( pChars, pChars + len, pBytes, pBytes + ( endIndex - curIndex ), out charsDecoded, out bytesDecoded );
        //        }
        //    }
        //    curIndex += bytesDecoded;
        //    return charsDecoded;
        //}

       


     

        internal  void Reset() {
            bitsFilled = 0;
            bits = 0;
        }

        internal  void SetNextOutputBuffer( Array buffer, int index, int count ) {
            Debug.Assert( buffer != null );
            Debug.Assert( count >= 0 );
            Debug.Assert( index >= 0 );
            Debug.Assert( buffer.Length - index >= count );
            Debug.Assert( ( buffer as byte[] ) != null );

            this.buffer = (byte[])buffer;
            this.startIndex = index;
            this.curIndex = index;
            this.endIndex = index + count;
        }

//
// Private methods
//
        private static byte[] ConstructMapBase64() {
            byte[] mapBase64 = new byte[MaxValidChar + 1];
            for ( int i = 0; i < mapBase64.Length; i++ ) {
                mapBase64[i]= Invalid;
            }
            for ( int i = 0; i < CharsBase64.Length; i++ ) {
                mapBase64[(int)CharsBase64[i]] = (byte)i;
            }
            return mapBase64;
        }
 





        private unsafe void Decode(byte* pChars, byte* pCharsEndPos,
                                   byte* pBytes, byte* pBytesEndPos,
                                   out int charsDecoded, out int bytesDecoded)
        {
#if DEBUG
            Debug.Assert(pCharsEndPos - pChars >= 0);
            Debug.Assert(pBytesEndPos - pBytes >= 0);
#endif

            // walk hex digits pairing them up and shoving the value of each pair into a byte
            byte* pByte = pBytes;
            byte* pChar = pChars;
            int b = bits;
            int bFilled = bitsFilled;

            while (pChar < pCharsEndPos && pByte < pBytesEndPos)
            {
                char ch = (char)*pChar;
                // end?
                if (ch == '=')
                {
                    break;
                }
                pChar++;

                // ignore white space
                if (char.IsWhiteSpace(ch))
                {
                    continue;
                }

                int digit;
                if (ch > 122 || (digit = MapBase64[ch]) == Invalid)
                {
                    throw new ArgumentException(
                        "InvalidBase64Value", new string((char *)pChars, 0, (int)(pCharsEndPos - pChars)));
                }

                b = (b << 6) | digit;
                bFilled += 6;

                if (bFilled >= 8)
                {
                    // get top eight valid bits
                    *pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF);
                    bFilled -= 8;

                    if (pByte == pBytesEndPos)
                    {
                        goto Return;
                    }
                }
            }

            if (pChar < pCharsEndPos && *pChar == '=')
            {
                bFilled = 0;
                // ignore padding chars
                do
                {
                    pChar++;
                } while (pChar < pCharsEndPos && *pChar == '=');

                // ignore whitespace after the padding chars
                if (pChar < pCharsEndPos)
                {
                    do
                    {
                        char charr = (char)*pChar++;
                        if (!(char.IsWhiteSpace(charr)) )
                        {  // if ( !( xmlCharType.IsWhiteSpace( chars[charPos++] ) ) ) {
                         
                            if (charr != '=')
                                throw new ArgumentException(("InvalidBase64Value  "+charr.ToString()));
                        }
                    } while (pChar < pCharsEndPos);
                }
            }

            Return:
            bits = b;
            bitsFilled = bFilled;

            bytesDecoded = (int)(pByte - pBytes);
            charsDecoded = (int)(pChar - pChars);
        }

        public static byte[] Decode(byte[] p)
        {
            Base64Decoder decoder = new Base64Decoder();
            decoder.outputStream = new MemoryStream();
            decoder.Decode(p, 0, p.Length);
            return ((MemoryStream)decoder.outputStream).ToArray();
        }
    }
}